<template>
  <!-- 金豆兑换弹窗 - 使用uni-popup -->
  <uni-popup ref="exchangePopup" type="bottom" :mask-click="true" :safe-area="false" :z-index="9999">
    <view cluni-popupass="exchange-popup-content">
      
      <!-- 兑换内容区域 -->
      <view class="exchange-content">
        <!-- 兑换红包标题 -->
        <view class="exchange-header">
          <text class="exchange-title">兑换红包</text>
          <view class="exchange-record" @tap="goToRecord">兑换记录 
		   <uni-icons type="right" color="#8B8B8B" size="20" ></uni-icons>
		  </view>
        </view>
        
        <!-- 兑换选项 -->
        <view class="exchange-options">
          <view 
            v-for="(option, index) in exchangeOptions" 
            :key="index"
            class="option-item"
            :class="{ active: selectedOption === index }"
            @tap="selectOption(index)"
          >
            <view class="option-beans">
              <text class="beans-amount">{{ option.beans }}</text>
              <view class="beans-icon">
                	<image class="reward-icon" src="/static/svip9.png" mode=""></image>
              </view>
            </view>
            <view class="option-yuan">¥{{ option.yuan }}
              	<image class="reward-hongbao" src="/static/hongbao.png" mode=""></image>
            </view>
          </view>
        </view>
        
        <!-- 我的金豆余额 -->
        <view class="balance-section">
          <text class="balance-text">我的金豆: {{ userBalance }}</text>
          <view class="balance-icon">
			                  	<image class="reward-icon" src="/static/svip9.png" mode=""></image>
			  ️</view>
        </view>
        
        <!-- 支付宝账户选择 -->
        <view class="alipay-section">
          <text class="alipay-title">兑换到以下支付宝</text>

          <!-- 已绑定支付宝时显示 -->
          <view v-if="userAlipay !== ''" class="alipay-options">
            <view class="alipay-item" @tap="selectAlipay(0)">
              <view class="alipay-info">
				<image class="alipay-logo" src="/static/svip8.png" mode=""></image>
                <text class="alipay-account">支付宝 ({{ formatAlipayAccount(userAlipay) }})</text>
              </view>
              <view class="radio-button" :class="{ active: selectedAlipay === 0 }"></view>
            </view>
          </view>

          <!-- 未绑定支付宝时显示 -->
          <view v-if="userAlipay === ''" class="alipay-options">
            <view class="alipay-item" @tap="goToBind">
              <view class="alipay-info">
               <image class="alipay-logo" src="/static/svip8.png" mode=""></image>
                <text class="alipay-account">未绑定支付宝账号</text>
              </view>
              <text class="arrow-icon">
				  	 <uni-icons type="right" color="#1B1E5F" size="20" ></uni-icons>
			  </text>
            </view>
          </view>
        </view>
        
        <!-- 兑换按钮 -->
        <button class="exchange-btn" @tap="handleExchange">兑换</button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { getToken, getCurrentUser, fetchUserInfo } from '../../utils/user.js'
import { REDPACKET_API } from '../../config/api.js'
import { getPublicConfig } from '../../utils/config.js'

// Emits
const emit = defineEmits<{
  close: []
  exchange: [data: { beans: number, yuan: number, alipayIndex: number }]
}>()

// 响应式数据
const selectedOption = ref(0)
const selectedAlipay = ref(0)
const exchangePopup = ref()
const exchangeOptions = ref([])
const userInfo = ref(null)

// 用户余额 - 从用户数据的bean字段读取
const userBalance = computed(() => {
  return userInfo.value?.bean || 0
})

// 用户支付宝信息
const userAlipay = computed(() => {
  return userInfo.value?.alipay || ''
})



// 获取兑换配置 - 从公共配置读取
const fetchExchangeConfig = async () => {
  try {
    // 从公共配置读取 red_packet_config
    const publicConfig = await getPublicConfig(false)
    console.log('公共配置数据:', publicConfig)

    const redPacketConfig = publicConfig?.app_config?.red_packet_config || []
    console.log('红包配置数据:', redPacketConfig)

    if (redPacketConfig.length > 0) {
      // 转换配置数据格式为组件需要的格式
      exchangeOptions.value = redPacketConfig.map(config => ({
        beans: config.withdraw_beans,
        yuan: parseFloat(config.red_packet).toFixed(2), // 保留两位小数
        daily_limit: config.daily_limit
      }))
      console.log('转换后的兑换配置:', exchangeOptions.value)
    } else {
      console.log('没有配置红包数据，使用默认配置')
      // 使用默认配置
      exchangeOptions.value = [
        { beans: 100, yuan: '1.00', daily_limit: 1 },
        { beans: 200, yuan: '2.00', daily_limit: 1 },
        { beans: 300, yuan: '3.00', daily_limit: 1 },
        { beans: 400, yuan: '4.00', daily_limit: 1 },
        { beans: 500, yuan: '5.00', daily_limit: 1 },
        { beans: 600, yuan: '6.00', daily_limit: 1 }
      ]
    }
  } catch (error) {
    console.error('获取兑换配置异常:', error)
    // 使用默认配置
    exchangeOptions.value = [
      { beans: 100, yuan: '1.00', daily_limit: 1 },
      { beans: 200, yuan: '2.00', daily_limit: 1 },
      { beans: 300, yuan: '3.00', daily_limit: 1 },
      { beans: 400, yuan: '4.00', daily_limit: 1 },
      { beans: 500, yuan: '5.00', daily_limit: 1 },
      { beans: 600, yuan: '6.00', daily_limit: 1 }
    ]
  }
}

// 获取用户信息
const fetchUserInfo = () => {
  try {
    const currentUser = getCurrentUser()
    if (currentUser) {
      userInfo.value = currentUser
      console.log('用户信息:', userInfo.value)
      console.log('用户金豆余额:', userBalance.value)
      console.log('用户支付宝:', userAlipay.value)
    } else {
      console.warn('未找到用户信息')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 方法
const selectOption = (index: number) => {
  selectedOption.value = index
}

const selectAlipay = (index: number) => {
  selectedAlipay.value = index
}

// 格式化支付宝账号显示
const formatAlipayAccount = (alipay: string) => {
  if (!alipay || alipay.trim() === '') {
    return '未绑定'
  }

  // 如果长度小于7位，直接返回原值
  if (alipay.length < 7) {
    return alipay
  }

  // 格式化为 145****263 格式（前3位 + 4个* + 后3位）
  const start = alipay.substring(0, 3)
  const end = alipay.substring(alipay.length - 3)
  return `${start}****${end}`
}

// 初始化数据
const initData = async () => {
  fetchUserInfo()
  await fetchExchangeConfig()
}

// 暴露给父组件的方法
const open = async () => {
  await initData()
  exchangePopup.value.open()
}

const close = () => {
  exchangePopup.value.close()
}

const goToRecord = () => {
  // 关闭当前弹窗
  close()
  emit('close')

  // 跳转到金豆兑换记录页面
  uni.navigateTo({
    url: '/pages/exchange-record/exchange-record'
  })
}

const goToBind = () => {
  // 关闭当前弹窗
  close()
  emit('close')

  // 跳转到个人信息页面绑定支付宝
  uni.navigateTo({
    url: '/pages/personal-info/personal-info'
  })
}

const handleExchange = async () => {
  const selectedData = exchangeOptions.value[selectedOption.value]
  console.log('选中的兑换数据:', selectedData)

  // 判断金豆余额是否足够
  if (userBalance.value < selectedData.beans) {
    uni.showToast({
      title: `金豆不足，需要${selectedData.beans}金豆`,
      icon: 'none',
      duration: 2000
    })
    return
  }

  // 检查是否已绑定支付宝
  if (userAlipay.value === '') {
    uni.showToast({
      title: '请先绑定支付宝账号',
      icon: 'none',
      duration: 2000
    })
    return
  }

  try {
    uni.showLoading({
      title: '兑换中...'
    })

    // 调用兑换红包API
    const token = getToken()
    if (!token) {
      throw new Error('未找到用户token，请重新登录')
    }

    const response = await uni.request({
      url: REDPACKET_API.EXCHANGE,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      data: {
        withdraw_beans: selectedData.beans
      }
    })

    console.log('兑换API响应:', response)

    if (response.statusCode === 200 && response.data.code === 200) {
      uni.hideLoading()
      uni.showToast({
        title: '兑换成功',
        icon: 'success'
      })

      // 兑换成功后刷新用户信息
      try {
        await fetchUserInfo()
        console.log('用户信息刷新成功')
      } catch (error) {
        console.error('刷新用户信息失败:', error)
      }

      // 发送兑换成功事件给父组件
      const exchangeData = {
        beans: selectedData.beans,
        yuan: selectedData.yuan,
        alipayIndex: selectedAlipay.value,
        daily_limit: selectedData.daily_limit
      }
      emit('exchange', exchangeData)

      // 立即关闭弹窗
      close()
      emit('close')

    } else {
      throw new Error(response.data?.message || '兑换失败')
    }

  } catch (error) {
    console.error('兑换失败:', error)
    uni.hideLoading()
    uni.showToast({
      title: error.message || '兑换失败，请重试',
      icon: 'error'
    })
  }
}

// 暴露方法给父组件
defineExpose({
  open,
  close
})
</script>

<style scoped>
/* 金豆兑换弹窗 - uni-popup内容 */
.exchange-popup-content {
  background: white;
  border-radius: 20rpx 20rpx 0 0;
  width: 100%;
  max-height: 80vh;
  overflow-y: auto;
  box-sizing: border-box;
  position: relative;
  z-index: 10000;
}

/* 顶部横幅 */
.banner {
  background: linear-gradient(135deg, #9C27B0 0%, #7B1FA2 100%);
  padding: 40rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  overflow: hidden;
}

.banner-left {
  flex: 1;
  z-index: 2;
}

.banner-title {
  font-size: 36rpx;
  font-weight: 800;
  color: white;
  display: block;
  margin-bottom: 10rpx;
  line-height: 1.2;
}

.banner-subtitle {
  font-size: 24rpx;
  color: white;
  opacity: 0.9;
}

.banner-right {
  position: relative;
  z-index: 2;
}

.robot-character {
  position: relative;
  width: 120rpx;
  height: 120rpx;
}

.robot-head {
  width: 80rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #9C27B0 0%, #7B1FA2 100%);
  border-radius: 40rpx;
  position: relative;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.robot-screen {
  width: 50rpx;
  height: 30rpx;
  background: #2196F3;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dollar-signs {
  font-size: 20rpx;
  color: white;
  font-weight: bold;
}

.robot-body {
  width: 60rpx;
  height: 25rpx;
  background: linear-gradient(135deg, #9C27B0 0%, #7B1FA2 100%);
  border-radius: 12rpx;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: -3rpx;
}
.reward-hongbao{
  width: 20rpx;
  height: 25rpx;
  margin-left: 5rpx;
}
.robot-x {
  font-size: 18rpx;
  color: white;
  font-weight: bold;
}

.robot-envelope {
  position: absolute;
  top: 15rpx;
  right: -15rpx;
  width: 30rpx;
  height: 30rpx;
  background: #F44336;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 3rpx 6rpx rgba(244, 67, 54, 0.3);
}

.envelope-icon {
  font-size: 16rpx;
}

.floating-coins {
  position: absolute;
  top: 5rpx;
  left: -25rpx;
}

.coin {
  font-size: 12rpx;
  display: block;
  margin-bottom: 6rpx;
  animation: float 2s ease-in-out infinite;
}
.reward-icon {
  width: 27rpx;
  height: 25rpx;
  margin-left: 5rpx;
}
.coin:nth-child(2) {
  animation-delay: 0.5s;
}

.coin:nth-child(3) {
  animation-delay: 1s;
}

@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-8rpx); }
}

/* 兑换内容区域 */
.exchange-content {
  padding: 30rpx;
  background-color: #fff;
}

.exchange-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.exchange-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
}

.exchange-record {
  font-size: 28rpx;
  color: #999;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.exchange-record:active {
  opacity: 0.7;
}

/* 兑换选项 */
.exchange-options {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.option-item {
  background: #F8F9FA;
  border: 2rpx solid #E9ECEF;
  border-radius: 12rpx;
  padding: 20rpx 10rpx;
  text-align: center;
  transition: all 0.3s ease;
}

.option-item.active {
  border-color: #4593FA;
  background: #F0F7FF;
}

.option-beans {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  margin-bottom: 8rpx;
}

.beans-amount {
  font-size: 24rpx;
  font-weight: 600;
  color: #333;
}

.beans-icon {
  font-size: 20rpx;
}

.option-yuan {
  font-size: 28rpx;
  font-weight: 600;
  color: #999999;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 余额部分 */
.balance-section {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8rpx;
  margin-bottom: 30rpx;
  padding: 20rpx;
  border-radius: 12rpx;
}

.balance-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #999999;
}

.balance-icon {
  font-size: 24rpx;
}

/* 支付宝部分 */
.alipay-section {
  margin-bottom: 40rpx;
}

.alipay-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.alipay-options {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.alipay-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background: #F8F9FA;
  border-radius: 12rpx;
  border: 2rpx solid #E9ECEF;
}

.alipay-info {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.alipay-logo {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
}

.alipay-account {
  font-size: 28rpx;
  color: #333;
}

.radio-button {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #D9D9D9;
  border-radius: 50%;
  position: relative;
}

.radio-button.active {
  border-color: #4593FA;
}

.radio-button.active::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 16rpx;
  height: 16rpx;
  background: #4593FA;
  border-radius: 50%;
}

.arrow-icon {
  font-size: 24rpx;
  color: #999;
}

/* 兑换按钮 */
.exchange-btn {
  width: 100%;
  height: 88rpx;
  background: #565FFD;
  color: white;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 15rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.exchange-btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

/* 覆盖uni-popup的默认样式 */
:deep(.uni-popup__wrapper) {
  padding-bottom: 0 !important;
  z-index: 9999 !important;
}

:deep(.uni-popup__wrapper.bottom) {
  padding-bottom: 0 !important;
  z-index: 9999 !important;
}

:deep(.uni-popup) {
  padding-bottom: 0 !important;
  z-index: 9999 !important;
}

:deep(.uni-popup__mask) {
  z-index: 9998 !important;
}

/* 确保弹窗内容在最顶层 */
:deep(.uni-popup__content) {
  z-index: 10000 !important;
  position: relative;
}
</style>
